// Created: Dec 13, 2014
//
// Author: wjinwen.1988@gmail.com

#include "chi/net/buffer.h"

#include <errno.h>
#include <sys/uio.h>

namespace chi {
namespace net {

ssize_t Buffer::ReadFd(int fd, int* save_errno) {
  char extrabuf[65536];
  struct iovec vec[2];
  const size_t writable = WritableBytes();
  vec[0].iov_base = Begin() + writer_index_;
  vec[0].iov_len = writable;
  vec[1].iov_base = extrabuf;
  vec[1].iov_len = sizeof(extrabuf);
  const ssize_t n = ::readv(fd, vec, 2);
  if (n < 0) {
    *save_errno = errno;
  } else if (static_cast<size_t>(n) <= writable) {
    writer_index_ += n;
  } else {
    writer_index_ = buffer_.size();
    Append(extrabuf, n - writable);
  }

  return n;
}

ssize_t Buffer::ReadTls(SSL* ssl, int* save_errno) {
  char buf[65536];
  ssize_t n = SSL_read(ssl, buf, 65536);
  if (n < 0) {
    *save_errno = errno;
  } else {
    Append(buf, n);
  }
  return n;
}

}
}
